/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador.autogenerats;

import controlador.autogenerats.exceptions.IllegalOrphanException;
import controlador.autogenerats.exceptions.NonexistentEntityException;
import entity.Producte;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.Produccio;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author David
 */
public class ProducteJpaController implements Serializable {

    public ProducteJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Producte producte) {
        if (producte.getProduccioCollection() == null) {
            producte.setProduccioCollection(new ArrayList<Produccio>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Produccio> attachedProduccioCollection = new ArrayList<Produccio>();
            for (Produccio produccioCollectionProduccioToAttach : producte.getProduccioCollection()) {
                produccioCollectionProduccioToAttach = em.getReference(produccioCollectionProduccioToAttach.getClass(), produccioCollectionProduccioToAttach.getId());
                attachedProduccioCollection.add(produccioCollectionProduccioToAttach);
            }
            producte.setProduccioCollection(attachedProduccioCollection);
            em.persist(producte);
            for (Produccio produccioCollectionProduccio : producte.getProduccioCollection()) {
                Producte oldProductesIdOfProduccioCollectionProduccio = produccioCollectionProduccio.getProductesId();
                produccioCollectionProduccio.setProductesId(producte);
                produccioCollectionProduccio = em.merge(produccioCollectionProduccio);
                if (oldProductesIdOfProduccioCollectionProduccio != null) {
                    oldProductesIdOfProduccioCollectionProduccio.getProduccioCollection().remove(produccioCollectionProduccio);
                    oldProductesIdOfProduccioCollectionProduccio = em.merge(oldProductesIdOfProduccioCollectionProduccio);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Producte producte) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Producte persistentProducte = em.find(Producte.class, producte.getId());
            Collection<Produccio> produccioCollectionOld = persistentProducte.getProduccioCollection();
            Collection<Produccio> produccioCollectionNew = producte.getProduccioCollection();
            List<String> illegalOrphanMessages = null;
            for (Produccio produccioCollectionOldProduccio : produccioCollectionOld) {
                if (!produccioCollectionNew.contains(produccioCollectionOldProduccio)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Produccio " + produccioCollectionOldProduccio + " since its productesId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Produccio> attachedProduccioCollectionNew = new ArrayList<Produccio>();
            for (Produccio produccioCollectionNewProduccioToAttach : produccioCollectionNew) {
                produccioCollectionNewProduccioToAttach = em.getReference(produccioCollectionNewProduccioToAttach.getClass(), produccioCollectionNewProduccioToAttach.getId());
                attachedProduccioCollectionNew.add(produccioCollectionNewProduccioToAttach);
            }
            produccioCollectionNew = attachedProduccioCollectionNew;
            producte.setProduccioCollection(produccioCollectionNew);
            producte = em.merge(producte);
            for (Produccio produccioCollectionNewProduccio : produccioCollectionNew) {
                if (!produccioCollectionOld.contains(produccioCollectionNewProduccio)) {
                    Producte oldProductesIdOfProduccioCollectionNewProduccio = produccioCollectionNewProduccio.getProductesId();
                    produccioCollectionNewProduccio.setProductesId(producte);
                    produccioCollectionNewProduccio = em.merge(produccioCollectionNewProduccio);
                    if (oldProductesIdOfProduccioCollectionNewProduccio != null && !oldProductesIdOfProduccioCollectionNewProduccio.equals(producte)) {
                        oldProductesIdOfProduccioCollectionNewProduccio.getProduccioCollection().remove(produccioCollectionNewProduccio);
                        oldProductesIdOfProduccioCollectionNewProduccio = em.merge(oldProductesIdOfProduccioCollectionNewProduccio);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = producte.getId();
                if (findProducte(id) == null) {
                    throw new NonexistentEntityException("The producte with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Producte producte;
            try {
                producte = em.getReference(Producte.class, id);
                producte.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The producte with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Produccio> produccioCollectionOrphanCheck = producte.getProduccioCollection();
            for (Produccio produccioCollectionOrphanCheckProduccio : produccioCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Producte (" + producte + ") cannot be destroyed since the Produccio " + produccioCollectionOrphanCheckProduccio + " in its produccioCollection field has a non-nullable productesId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(producte);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Producte> findProducteEntities() {
        return findProducteEntities(true, -1, -1);
    }

    public List<Producte> findProducteEntities(int maxResults, int firstResult) {
        return findProducteEntities(false, maxResults, firstResult);
    }

    private List<Producte> findProducteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Producte.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Producte findProducte(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Producte.class, id);
        } finally {
            em.close();
        }
    }

    public int getProducteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Producte> rt = cq.from(Producte.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
